<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\Technical;
use app\model\TechnicalLevel;
use app\model\Geocoder;
use app\model\Agent;
use app\model\Member;
use app\model\Store;
use app\model\Operatingcity;
use app\model\OperatingcityLevel;
use app\model\OperatingcityType;
use app\model\RegisterField;
use app\model\Area;
use app\model\MemberAuthGroup;
use app\model\Category;
use app\model\StoreCate;
use app\model\Users;

class DiyfieldsController extends Base
{
    function getModel()
    {
        $ptype = $this->getPath()[1];
        if ($ptype == 'technical') {
            return new Technical;
        } else if ($ptype == 'agent') {
            return new Agent;
        } else if ($ptype == 'member') {
            return new Member;
        } else if ($ptype == 'operatingcity') {
            return new Operatingcity;
        } else if ($ptype == 'store') {
            return new Store;
        }
    }

    function getPath()
    {
        $path = input('post.path', '', 'serach_in');
        $tmppath = explode('/', $path);
        $con = input('con');
        if (!empty($con)) {
            $tmppath[1] = $con;
        }
        return $tmppath;
    }

    function index()
    {
        $uniacid = uniacid();
        $page = input('post.page', 1, 'intval');
        $ptype = $this->getPath()[1];

        $Fielddata = RegisterField::where(['uniacid' => $uniacid, 'ptype' => $ptype])->select()->toArray();

        if (empty($Fielddata)) {
            RegisterField::datainitial($ptype);
        }

        $query = $this->setSearch();

        $res = $query->order('sort asc,id desc')
            // ->fetchSql(true)->select();
            ->paginate(getpage())
            ->toArray();

        // halt($res);

        if (!empty($res['data'])) {
            foreach ($res['data'] as &$vo) {
                if ($ptype == 'member') {
                    $vo['gid'] = MemberAuthGroup::getgroupName($vo['gid']);
                    $vo['pid'] = Member::get_name($vo['pid']) ?? '平台';
                    $vo['regdate'] = time_format($vo['regdate']);
                    $vo['lastdate'] = time_format($vo['lastdate']);
                }
                if ($ptype == 'technical') {

                    $vo['cate_ids'] = Category::getmultiple($vo['cate_ids']) ?? '无';
                    $vo['level'] = TechnicalLevel::getTitle($vo['level']) ?? '初级';
                    $vo['sid'] = Store::getTitle($vo['sid']) ?? '平台';
                    $vo['coordinate'] = '经度：'.$vo['longitude'].'；纬度：'.$vo['latitude'];
                }
                if ($ptype == 'store') {
                    if (empty($vo['stid'])) {
                        $vo['stid'] = '未设置';
                    } else {
                        $vo['stid'] = StoreCate::getTitle($vo['stid']);
                    }

                    if ($vo['end_time'] == 0) {
                        $vo['end_time'] = '永久有效';
                    } else {
                        $vo['end_time'] = time_format($vo['end_time']);
                    }
                    $vo['cate_ids'] = Category::getmultiple($vo['cate_ids']) ?? '无';
                }
                if ($ptype == 'operatingcity') {

                    if ($vo['end_time'] == 0) {
                        $vo['end_time'] = '永久有效';
                    } else {
                        $vo['end_time'] = time_format($vo['end_time']);
                    }
                    $vo['cate_ids'] = Category::getmultiple($vo['cate_ids']) ?? '无';
                    $vo['level'] = OperatingcityLevel::getTitle($vo['level']) ?? '初级';
                    $vo['areatype'] = OperatingcityType::getTitle($vo['areatype']) ?? '未设置';
                }
                if (!empty($vo['uuid'])) {
                    $vo['username'] = Users::getusername($vo['uuid']);
                }
                $vo['province_id'] = $vo['province_name'] . $vo['city_name'] . $vo['district_name'];

                // $vo['create_time'] = time_format($vo['create_time']);
            }
        }
        $data['data'] = $res;
        $data['controller'] = $this->getPath()[1];
        $data['action'] = $this->getPath()[2];
        if ($page == 1) {
            $data['field_data']['RegisterField'] = RegisterField::getlistViewField($ptype);
        }

        return $this->json($data);
    }

    function setSearch()
    {
        $keyword = trim(input('post.keyword', '', 'serach_in'));
        $status = input('post.status', '', 'serach_in');
        $uniacid = uniacid();

        if ($this->getPath()[2] == "audit") {
            $status = "0";
        }
        $query = $this->getModel()->where(['uniacid' => $uniacid]);

        if ($this->getPath()[1] == "technical") {
            if (!empty($this->sid)) {
                $query->where('sid', $this->sid);
            }
        }
        if ($this->getPath()[1] == "technical" || $this->getPath()[1] == "store") {
            if (!empty($this->ocid)) {
                $query->where('ocid', $this->ocid);

                $Operatingcitydata = Operatingcity::find($this->ocid);
                if ($Operatingcitydata) {
                    $Operatingcitydata = $Operatingcitydata->toArray();

                    if ($Operatingcitydata['areatype'] == 2) {
                        // $query->where('district_name', $Operatingcitydata['district_name']);
                    } elseif ($Operatingcitydata['areatype'] == 1) {
                        // $query->where('city_name', $Operatingcitydata['city_name']);
                    }
                }
            }
        }

        if (!empty($keyword)) {

            if ($this->getPath()[1] == "member") {
                $query->where('nickname|telephone', 'like', '%' . $keyword . '%');
            } elseif ($this->getPath()[1] == "technical") {
                $query->where('title|tel', 'like', '%' . $keyword . '%');
            } elseif ($this->getPath()[1] == "agent") {
                $query->where('title|tel', 'like', '%' . $keyword . '%');
            } elseif ($this->getPath()[1] == "store") {
                $query->where('title|tel', 'like', '%' . $keyword . '%');
            }
        }

        if (!empty($status) || $status === "0") {
            $query->where(['status' => $status]);
        }
        return $query;
    }

    function listUpdate()
    {
        $data = only('id,status');
        if (!$data['id']) throw new ValidateException('参数错误');
        $this->getModel()->update($data);

        return $this->json(['msg' => '操作成功']);
    }

    public function update()
    {
        $id = $this->request->post('id');
        $uuid = $this->request->post('uuid');
        $postdata = only('id,fields');
        $data = RegisterField::fieldToData($postdata['fields']);
        if ($data['username'] && empty($id)) {
            $data['uuid'] = uniqid(rand(1, 10000));
        }
        $usersdata['password'] = $data['password'];
        unset($data['password']);
        if (empty($id)) {
            $usersdata['username'] = trim($data['username']);
        }
        unset($data['username']);

        if ($usersdata['username']) {
            if (Users::where('username', $usersdata['username'])->find()) {
                throw new ValidateException('用户名已被占用');
            }
        }
        if ($this->getPath()[1] == 'store') {
            if (empty($data['latitude']) && empty($data['longitude']) && !empty($data['province_id']) && isset($data['address']) && $data['address']) {
                $coder = Geocoder::geocoding($data['province_name'] . $data['city_name'] . $data['district_name'] . $data['address']);
                $data['latitude'] = $coder['latitude'];
                $data['longitude'] = $coder['longitude'];
                $data['province'] = $data['province_id'];
                $data['city'] = $data['city_id'];
                $data['district'] = $data['district_id'];
            }
        }
//        else if ($this->getPath()[1] == 'technical') {
//            if (empty($data['latitude']) && empty($data['longitude']) &&
//                !empty($data['province_name']) && !empty($data['city_name']) && !empty($data['district_name'])
//                && $data['region_name']) {
//                $coder = Geocoder::geocoding($data['province_name'] . $data['city_name'] . $data['district_name'] . $data['region_name']);
//                $data['latitude'] = $coder['latitude'];
//                $data['longitude'] = $coder['longitude'];
//            }
//        }

        if (empty($id)) {
            $data['uid'] = 0;
            $data['uniacid'] = uniacid();
            $data['sort'] = 100;
            $data['create_time'] = time();
            $data['sid'] = $this->sid;
            $data['ocid'] = $this->ocid;
            try {

                $res = $this->getModel()->create($data);
                if ($this->getPath()[1] == 'store' || $this->getPath()[1] == 'technical' || $this->getPath()[1] == 'operatingcity') {

                    if ($res->id && !empty($usersdata['username'])) {
                        if (!empty($usersdata['password'])) {
                            $usersdata["salt"] = substr(md5(uniqid()), 8, 8);
                            $usersdata['password'] = pass_hash($usersdata['password'], $usersdata["salt"]);
                        } else {
                            unset($usersdata['password']);
                        }
                        if ($this->getPath()[1] == 'technical') {
                            $usersdata['sid'] = $res->id;
                        }
                        if ($this->getPath()[1] == 'store') {
                            $usersdata['sid'] = $res->id;
                        }
                        if ($this->getPath()[1] == 'operatingcity') {
                            $usersdata['ocid'] = $res->id;
                        }

                        $usersdata['uniacid'] = uniacid();
                        $usersdata['uuid'] = $data['uuid'];
                        $usersdata['w7uid'] = 0;
                        $usersdata['create_time'] = time();
                        Users::create($usersdata);
                    }
                }
            } catch (\Exception $e) {
                throw new ValidateException($e->getMessage());
            }
            return $this->json(['msg' => '添加成功', 'data' => $res->id]);
        } else {
            $data['id'] = $id;
            try {

                if (!empty($usersdata['password']) && $uuid) {
                    $data["salt"] = $usersdata["salt"] = substr(md5(uniqid()), 8, 8);
                    $data["password"] = $usersdata['password'] = pass_hash($usersdata['password'], $usersdata["salt"]);

                    Users::where('uuid', $uuid)->update($usersdata);
                } else {
                    unset($usersdata['password']);
                }

                $this->getModel()->update($data);
            } catch (\Exception $e) {
                throw new ValidateException($e->getMessage());
            }
            return $this->json(['msg' => '操作成功']);
        }
    }

    public function audit()
    {
        $id = $this->request->post('id');
        $data['id'] = $id;
        $data['update_time'] = time();
        $data['status'] = 1;

        try {
            $this->getModel()->update($data);
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
        return $this->json(['msg' => '审核成功']);
    }

    function getInfo()
    {
        $id = $this->request->post('id', '', 'serach_in');
        $ptype = $this->getPath()[1];
        $data = RegisterField::getinputField($ptype);

        if (!empty($id)) {

            $infodata = $this->getModel()->find($id);

            if (!empty($infodata)) {
                $infodata = $infodata->toArray();
                $infodata['password'] = "";

                if (!empty($infodata['uuid'])) {
                    $infodata['username'] = Users::getusername($infodata['uuid']);
                }

                if (empty($infodata['province_id']) && !empty($infodata['province_name'])) {
                    $infodata['province_id'] = Area::get_area_id($infodata['province_name']);
                }
                if (empty($infodata['city_id']) && !empty($infodata['city_name'])) {
                    $infodata['city_id'] = Area::get_area_id($infodata['city_name']);
                }
                if (empty($infodata['district_id']) && !empty($infodata['district_name'])) {
                    $infodata['district_id'] = Area::get_area_id($infodata['district_name']);
                }

                $area[0] = $infodata['province_id'];
                $area[1] = $infodata['city_id'];
                if (!empty($infodata['district_id'])) {
                    $area[2] = $infodata['district_id'];
                }

                $infodata['province_id'] = $area;

                $longitude = 0;
                if(!empty($infodata['longitude'])) {
                    $longitude = (float)$infodata['longitude'];
                }

                $latitude = 0;
                if(!empty($infodata['latitude'])) {
                    $latitude = (float)$infodata['latitude'];
                }

                $infodata['coordinate'] = ["lng"=>$longitude,"lat"=>$latitude];
                $customtext = iunserializer($infodata['customtext']);
            }
        }

        foreach ($data as &$vo) {

            if ($vo['is_sys'] == 1) {
                $vo['fieldsvalue'] = $infodata[$vo['fieldsmingcheng']];
                if ($vo['fieldsmingcheng'] == "sex") {
                    $vo['selectvaluearray'] = sexarray();
                }
                if ($vo['fieldsmingcheng'] == "province_id") {
                    $vo['viewmingcheng'] = '地区';
                }
                if ($vo['fieldsmingcheng'] == "city_id" || $vo['fieldsmingcheng'] == "district_id") {
                    $vo = '';
                }

                if ($vo['fieldsmingcheng'] == 'category_id') {
                    $vo['selectvaluearray'] = \app\model\TechnicalCategory::getpcarray();
                }

                if ($vo['fieldsmingcheng'] == 'sid') {
                    $vo['selectvaluearray'] = Store::getpcarray();
                }

                if ($vo['fieldsmingcheng'] == 'level') {
                    if ($vo['ptype'] == 'technical') {
                        $vo['selectvaluearray'] = \app\model\TechnicalLevel::getpcarray();
                    } elseif ($vo['ptype'] == 'operatingcity') {
                        $vo['selectvaluearray'] = \app\model\OperatingcityLevel::getpcarray();
                    }
                }
                if ($vo['fieldsmingcheng'] == 'areatype') {
                    $vo['selectvaluearray'] = \app\model\OperatingcityType::getpcarray();
                }
                if ($vo['fieldsmingcheng'] == 'stid') {
                    $vo['selectvaluearray'] = StoreCate::getpcarray();
                }

                if ($vo['fieldsmingcheng'] == 'consulting_id') {
                    $vo['selectvaluearray'] = \app\model\Goods::getpcarray();
                }
                if ($vo['fieldsmingcheng'] == 'gid') {
                    $vo['selectvaluearray'] = \app\model\MemberAuthGroup::getpcarray();
                }

                if ($vo['inputtype'] == 'checkbox' && $vo['fieldsmingcheng'] == 'cate_ids') {
                    if (empty($vo['fieldsvalue'])) {
                        $vo['fieldsvalue'] = [];
                    } else {
                        $vo['fieldsvalue'] = explode(',', $vo['fieldsvalue']);
                    }
                    $vo['selectvaluearray'] = Category::gettoparray();
                }
            } else {
                $vo['fieldsvalue'] = $customtext[$vo['inputtype']][$vo['id']];
            }
            if (!empty($vo['selectvalue'])) {
                $selectvaluearray = explode(',', $vo['selectvalue']);
                if (is_array($selectvaluearray)) {
                    foreach ($selectvaluearray as $key => $svo) {
                        $vo['selectvaluearray'][$key]['val'] = $svo;
                        $vo['selectvaluearray'][$key]['key'] = $svo;
                    }
                }
            }
        }
        $retdata['id'] = $infodata['id'];
        $retdata['uuid'] = $infodata['uuid'];
        $retdata['fields'] = $data;

        return $this->json(['data' => $retdata]);
    }

    function delete()
    {
        $idx = $this->request->post('id', '', 'serach_in');
        if (!$idx) throw new ValidateException('参数错误');

        $this->getModel()->destroy(['id' => explode(',', $idx)], true);
        return $this->json(['msg' => '操作成功']);
    }

    /*
     *  导入
     */
    public function importData()
    {
        $data = $this->request->post();
        $ptype = $this->getPath()[1];
        $uniacid = uniacid();
        $list = [];

        $importField = RegisterField::getimportField($ptype);

        foreach ($data as $k => $v) {

            $info['uniacid'] = $uniacid;

            foreach ($importField as $key => $fvo) {

                if ($fvo['inputtype'] == 'text' || $fvo['inputtype'] == 'textarea') {
                    if ($fvo['is_sys'] == 1) {
                        $info[$fvo['fieldsmingcheng']] = $v[$fvo['viewmingcheng']];
                    } else {
                        $customtext['text'][$fvo['id']] = $v[$fvo['viewmingcheng']];
                    }
                } elseif ($fvo['inputtype'] == 'select') {
                    if ($fvo['is_sys'] == 1) {
                        $info[$fvo['fieldsmingcheng']] = $v[$fvo['viewmingcheng']];
                    } else {
                        $customtext['select'][$fvo['id']] = $v[$fvo['viewmingcheng']];
                    }
                } elseif ($fvo['inputtype'] == 'radio') {
                    if ($fvo['is_sys'] == 1) {
                        if ($fvo['fieldsmingcheng'] == "sex") {
                            if ($v[$fvo['viewmingcheng']] == '保密') {
                                $info[$fvo['fieldsmingcheng']] = 0;
                            } elseif ($v[$fvo['viewmingcheng']] == '男') {
                                $info[$fvo['fieldsmingcheng']] = 1;
                            } elseif ($v[$fvo['viewmingcheng']] == '女') {
                                $info[$fvo['fieldsmingcheng']] = 2;
                            }
                        }
                    } else {
                        $customtext['radio'][$fvo['id']] = $v[$fvo['viewmingcheng']];
                    }
                } elseif ($fvo['inputtype'] == 'radio') {
                    if ($fvo['is_sys'] == 1) {
                        $info[$fvo['fieldsmingcheng']] = $v[$fvo['viewmingcheng']];
                    } else {
                        $customtext['radio'][$fvo['id']] = $v[$fvo['viewmingcheng']];
                    }
                }
            }

            $info['customtext'] = serialize($customtext);

            $info['regdate'] = time();
            $info['lastdate'] = time();
            $info['create_time'] = time();

            $is_repeat = 0;

            if (empty($is_repeat)) {
                $this->getModel()->create($info);
                //$list[$k] = $info;
            }
        }
        return $this->json(['msg' => '操作成功']);
    }

    function dumpdata()
    {
        $page = $this->request->post('page', 1, 'intval');
        $limit = config('my.dumpsize') ? config('my.dumpsize') : 1000;
        $ptype = $this->getPath()[1];

        $query = $this->setSearch();

        $count = $query->count();

        $res = $query->order('id desc')
            ->limit(($page - 1) * $limit, $limit)
            ->select()
            ->toArray();

        foreach ($res as $key => $val) {
            $res[$key]['sex'] = getItemVal($val['sex'], '[{"key":"男","val":"1","label_color":""},{"key":"女","val":"2","label_color":""}]');
            $res[$key]['status'] = getItemVal($val['status'], '[{"key":"开启","val":"1"},{"key":"关闭","val":"0"}]');
            $res[$key]['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
        }
        $importField = RegisterField::getimportField($ptype);
        $datalist = [];
        if (!empty($res)) {
            foreach ($res as $k => $vo) {

                foreach ($importField as $key => $fvo) {

                    if ($fvo['inputtype'] == 'text' || $fvo['inputtype'] == 'textarea') {
                        if ($fvo['is_sys'] == 1) {
                            $datalist[$k][$fvo['fieldsmingcheng']] = $vo[$fvo['fieldsmingcheng']];
                        } else {
                            $datalist[$k][$fvo['inputtype'] . $fvo['id']] = iunserializer($vo['customtext'])[$fvo['inputtype']][$fvo['id']];
                        }
                    } elseif ($fvo['inputtype'] == 'select') {
                        if ($fvo['is_sys'] == 1) {
                        } else {
                            $datalist[$k][$fvo['inputtype'] . $fvo['id']] = iunserializer($vo['customtext'])[$fvo['inputtype']][$fvo['id']];
                        }
                    } elseif ($fvo['inputtype'] == 'radio') {
                        if ($fvo['is_sys'] == 1) {
                            if ($fvo['fieldsmingcheng'] == "sex") {
                                if ($vo[$fvo['fieldsmingcheng']] == '0') {
                                    $datalist[$k]['sex'] = '保密';
                                } elseif ($vo[$fvo['fieldsmingcheng']] == '1') {
                                    $datalist[$k]['sex'] = '男';
                                } elseif ($vo[$fvo['fieldsmingcheng']] == '1') {
                                    $datalist[$k]['sex'] = '女';
                                }
                            } else {
                                $datalist[$k][$fvo['fieldsmingcheng']] = $vo[$fvo['fieldsmingcheng']];
                            }
                        } else {
                            $datalist[$k][$fvo['inputtype'] . $fvo['id']] = iunserializer($vo['customtext'])[$fvo['inputtype']][$fvo['id']];
                        }
                    } elseif ($fvo['inputtype'] == 'radio') {
                        if ($fvo['is_sys'] == 1) {
                            $datalist[$k][$fvo['fieldsmingcheng']] = $vo[$fvo['fieldsmingcheng']];
                        } else {
                            $datalist[$k][$fvo['inputtype'] . $fvo['id']] = iunserializer($vo['customtext'])[$fvo['inputtype']][$fvo['id']];
                        }
                    }
                    //$ii = $key;
                }
            }
        }

        foreach ($importField as $key => $vo) {
            $data['header'][$key] = $vo['viewmingcheng'];
        }
        //var_dump($datalist);
        //var_dump($res);

        $data['percentage'] = ceil($page * 100 / ceil($count / $limit));
        $data['filename'] = '数据.' . config('my.dump_extension');
        $data['data'] = $datalist;
        return $this->json($data);
    }

    public function get_idbytitle($list, $title)
    {
        foreach ($list as $v) {
            if ($v['key'] == $title) {
                return $v['val'];
            }
        }
        return 0;
    }

    public function get_idbyarea_name($list, $area_name)
    {
        foreach ($list as $v) {
            if ($v['area_name'] == $area_name) {
                return $v['area_id'];
            }
        }
        return 0;
    }
}
